package com.lczyfz.istep.modules.openstack.utils;


import com.lczyfz.istep.modules.openstack.configure.PropertyOpt;
import com.lczyfz.istep.modules.openstack.constvary.RequestType;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * ��װhttpConnection
 * @author jm
 */
public class HTTP {

	public static PropertyOpt properties = PropertyOpt.getInstance();

	/**
	 * ������Ӧresponse����
	 * @param request ������
	 * @return
	 */
	public static Response getConnectionResult(Request request){
		Response response = new Response();
		HttpURLConnection httpConnection = null;
		try {
			URL targetUrl = new URL(request.getHost()+request.getUrl());
			httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setConnectTimeout(30000);
			httpConnection.setReadTimeout(30000);
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod(request.getRequestType().toString());
			httpConnection.setRequestProperty("Content-Type", "application/json");
			if( null != request.getHeader()){
				for(Map.Entry<String, String> property : request.getHeader().entrySet()){
					httpConnection.setRequestProperty(property.getKey() , property.getValue());
				}
			}
			if( needOutPutStream(request.getRequestType()) && null != request.getBody()){
				OutputStream outputStream = httpConnection.getOutputStream();
				outputStream.write(request.getBody().toString().getBytes());
				outputStream.flush();
			}

			try{
				BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
				response.setResponseCode(httpConnection.getResponseCode());
				/**�����ɾ���Ļ�**/
				if( RequestType.DELETE.equals(request.getRequestType())){
					return response;
				}
				String result = "";
				String output;
				while ((output = responseBuffer.readLine()) != null) {
					result += output;
				}
				response.setResponseBody(result == "" ? null :  JSONObject.fromObject(result));
			}catch(IOException e){
				e.printStackTrace();
				response.setResponseCode(httpConnection.getResponseCode());
			}
			if(null != request.getExpectHeader() ){
				Map<String , Object> responseHeader = new HashMap<String,Object>();
				for(String key : request.getExpectHeader()){
					responseHeader.put(key, httpConnection.getHeaderField(key));
				}
				response.setResponseHeader(responseHeader);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch(IOException e){
			e.printStackTrace();
		}finally{
			httpConnection.disconnect();
		}
		return response;
	}

	@SuppressWarnings("resource")
	public static Response uploadConnection(Request request ,InputStream inputStream){
		Response response = new Response();
		HttpURLConnection httpConnection = null;
		try {
			URL targetUrl = new URL(request.getHost()+request.getUrl());
			httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setConnectTimeout(30000);
			httpConnection.setReadTimeout(30000);
			httpConnection.setChunkedStreamingMode(0);//不使用HttpURLConnection的缓存机制，直接将流提交到服务器上。
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod(request.getRequestType().toString());
			httpConnection.setRequestProperty("Content-Type", "application/octet-stream");
			if( null != request.getHeader()){
				for(Map.Entry<String, String> property : request.getHeader().entrySet()){
					httpConnection.setRequestProperty(property.getKey() , property.getValue());
				}
			}

			OutputStream outputStream = httpConnection.getOutputStream();
			BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
			int len = 1024;
			byte[] bits = new byte[len];
			while( (len = bufferedInputStream.read(bits)) != -1){
				outputStream.write(bits,0,len);
			}
			outputStream.flush();
			outputStream.close();
			httpConnection.getInputStream();
			response.setResponseCode(httpConnection.getResponseCode());

		}catch(IOException e){
			e.printStackTrace();
		}finally{
			httpConnection.disconnect();
		}
		return response;
	}

	/**
	 * ����Ƿ�������
	 * ֮ǰ����ÿ����������֮�󷵻�HttpURLConnection����
	 * Ȼ���ڷ����ڲ�ȥ����header��body
	 * ������������������ڲ���Ҫȥ���쳣��Ҳ�Ƚ��鷳
	 * ���Ը�getConnectionResult������
	 * ���Ƿ�ֹ�������⣬���Ի��Ǵ�һ��
	 * @param restfulurl
	 * @param header
	 * @param params
	 * @param methods
	 * @return
	 */
	@Deprecated
	public static HttpURLConnection getHttpConnection(String restfulurl, Map<String,String> header , JSONObject params ,String methods) {

		HttpURLConnection httpConnection = null;
		try {
			PropertyOpt properties = PropertyOpt.getInstance();
			String url = properties.getRestfulurl();
//			System.out.println(url+restfulurl);
			URL targetUrl = new URL(url+restfulurl);

			httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod(methods);
			httpConnection.setRequestProperty("Content-Type", "application/json");

			if( null != header){
				for(Map.Entry<String, String> property : header.entrySet()){
					httpConnection.setRequestProperty(property.getKey() , property.getValue());
				}
			}
			OutputStream outputStream = httpConnection.getOutputStream();
			if( null != params){
				outputStream.write(params.toString().getBytes());
			}
			outputStream.flush();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch(IOException e){
			e.printStackTrace();
		}
		return httpConnection;
	}

	public static boolean needOutPutStream(RequestType type){
		switch(type){
			case POST:
			case PUT:
			case DELETE:
			case PATCH: return true ;
			default:
				return false;
		}
	}


}
